package com.flycms.config;

import com.flycms.filter.CustomFormAuthenticationFilter;
import com.flycms.filter.CustomLogoutFilter;
import com.flycms.modules.shiro.MyCredentialsMatcher;
import com.flycms.modules.shiro.MyShiroRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Biz-Boot, All rights reserved
 * 版权：企业之家网 -- 企业建站管理系统<br/>
 * 开发公司：97560.com<br/>
 *
 * @author sun-kaifei
 * @version 1.0 <br/>
 * @email 79678111@qq.com
 * @Date: 0:32 2019/8/15
 */

@Configuration
public class ShiroConfig {

    private Logger log = LoggerFactory.getLogger(ShiroConfig.class);

    /**
     * Session会话管理器,session交给shiro管理
     */
    @Bean
    public DefaultWebSessionManager sessionManager(@Value("${myframe.sessionTimeout:3600}") long globalSessionTimeout){
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        //是否开启会话验证器，默认是开启的
        sessionManager.setSessionValidationSchedulerEnabled(true);
        //禁止URL地标后面添加JSESSIONID
        sessionManager.setSessionIdUrlRewritingEnabled(false);
        //设置全局会话超时时间
        sessionManager.setGlobalSessionTimeout(globalSessionTimeout * 1000);
        sessionManager.setSessionValidationInterval(globalSessionTimeout * 1000);
        return sessionManager;
    }

    // 配置加密方式
    // 配置了一下，这货就是验证不过，，改成手动验证算了，以后换加密方式也方便
    @Bean
    public MyCredentialsMatcher myCredentialsMatcher() {
        return new MyCredentialsMatcher();
    }

    @Bean
    public MyShiroRealm myShiroRealm() {
        MyShiroRealm myShiroRealm = new MyShiroRealm();
        myShiroRealm.setCredentialsMatcher(myCredentialsMatcher());
        return myShiroRealm;
    }

    /**
     * 安全管理器
     * @param sessionManager
     * @return
     */
    @Bean("securityManager")
    public SecurityManager securityManager( SessionManager sessionManager) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myShiroRealm());
        securityManager.setRememberMeManager(null);
        securityManager.setSessionManager(sessionManager);
        return securityManager;
    }

    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        // Shiro的核心安全接口,这个属性是必须的
        shiroFilter.setSecurityManager(securityManager);
        // 获取filters
        Map<String, Filter> filters = shiroFilter.getFilters();
        // 将自定义的FormAuthenticationFilter注入shiroFilter中
        filters.put("authc", new CustomFormAuthenticationFilter());
        // 将自定义的LogoutFilter注入shiroFilter中
        filters.put("logout", new CustomLogoutFilter());
        shiroFilter.setFilters(filters);
        // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
        shiroFilter.setLoginUrl("/system/login.do");
        shiroFilter.setUnauthorizedUrl("/403.do");



        // 拦截器.
        Map<String, String> filterMap = new LinkedHashMap<String, String>();
        filterMap.put("/member/login.do", "anon");
        filterMap.put("/member/register.do", "anon");
        filterMap.put("/member/sms_code.do", "anon");
        filterMap.put("/403.do", "roles");
        filterMap.put("/404.do", "anon");
        filterMap.put("/500.do", "anon");
        filterMap.put("/logout", "logout");
        filterMap.put("/admin/**", "authc");
        filterMap.put("/member/**", "authc");
        filterMap.put("/member/**", "authc");
        filterMap.put("/agency/**", "authc");
        filterMap.put("/403.do", "roles");
        filterMap.put("/**", "anon");

        // 配置退出过滤器,其中的具体的退出代码Shiro已经替我们实现了，登出后跳转配置的loginUrl
        shiroFilter.setFilterChainDefinitionMap(filterMap);
        return shiroFilter;
    }

    /**
     * Shiro生命周期处理器,保证实现了Shiro内部lifecycle函数的bean执行
     * @return
     */
    @Bean("lifecycleBeanPostProcessor")
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    /**
     *  开启Shiro的注解(如@RequiresRoles,@RequiresPermissions)
     * @return
     */
    @Bean
    public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator(){
        DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        advisorAutoProxyCreator.setProxyTargetClass(true);
        return advisorAutoProxyCreator;
    }

    //加入注解的使用，不加入这个注解不生效
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("securityManager")
                                                                                           SecurityManager
                                                                                           securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    @Bean
    @ConditionalOnMissingBean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator();
        defaultAAP.setProxyTargetClass(true);
        return defaultAAP;
    }
}
